import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"
import createPersistedState from 'vuex-persistedstate';
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    folderTo:null,
    folders:[],
    emailList:[],
    emailId:null,
    selectInputTo:'',
    currentComponent:'MailboxHome',
    user: null,

  },

  mutations: {
    updateFolderId(state,folderTo){
      state.folderTo = folderTo;
    },
    setFolders(state,folders){
      state.folders = folders;
    },
    setEmailList(state,emailList){
      state.emailList = emailList;
    },
    setEmailStarList(state,emailList){
      state.emailList = emailList;
    },
    setEmailId(state,emailId){
      state.emailId = emailId;
    },
    setSearchInput(state,selectInputTo){
      state.selectInputTo = selectInputTo;
    },
    replaceComponent(state, componentName) {
      state.currentComponent = componentName;
    },
    setUser(state, userInfo) {
      state.user = userInfo
    },
    logout(state) {
      state.user = null
    },

  },
  getters: {
    folderTo:state => state.folderTo,
    selectInputTo:state => state.selectInputTo,

  },
  actions: {
    //定义异步或批处理操作状态管理
    moveEmail({ state }, { emailId, folderId }) {
      // 调用后端API移动邮件
      axios.post("http://localhost:8989/email/move", {
        emailId: emailId,
        folderId: folderId
      }).then(res => {
        // 移动成功后，更新状态
        state.emailList.forEach(email => {
          if (email.folderId === emailId) {
            email.folderId = folderId;
          }
        });
      });
      // ...
    },
    replaceComponent({ commit }, componentName) {
      commit('replaceComponent', componentName);
    },

    },
  modules: {

  },
  plugins: [
    createPersistedState({
      // 可以指定需要持久化的state
      paths: ['folders', 'folderTo', 'emailId', 'emailList', 'selectInputTo','user']
    })
  ]
})
